package feishuUtil

import (
	"encoding/json"
	"go-api-template/service"
	"io"
	"io/ioutil"
	"net/http"
	"strings"
)

type FeishuClientI interface {
	GetTenantAccessToken() (string, error)
	loadConf() error
	request(method string, apiPath string, payload *strings.Reader) ([]byte, error)
}

type FeishuClient struct {
	TenantAccessToken string `json:"tenant_access_token"`
	appId             string
	appSecret         string
}

func (fc *FeishuClient) request(method string, apiPath string, payload *strings.Reader) (bs []byte, err error) {
	client := &http.Client{}
	req, err := http.NewRequest(method, "https://open.feishu.cn"+apiPath, payload)
	if err != nil {
		return nil, err
	}
	req.Header.Add("MessageContent-Type", "application/json")
	req.Header.Add("Authorization", "Bearer "+fc.TenantAccessToken)
	res, err := client.Do(req)
	if res != nil {
		defer func(Body io.ReadCloser) {
			err = Body.Close()
		}(res.Body)
		bs, err = ioutil.ReadAll(res.Body)
		if err != nil {
			return nil, err
		}
	}
	return
}

func (fc *FeishuClient) GetTenantAccessToken() (err error) {
	bs, err := fc.request("POST", "/open-apis/auth/v3/tenant_access_token/internal", strings.NewReader("{\"app_id\":\""+fc.appId+"\",\"app_secret\":\""+fc.appSecret+"\"}"))
	if err != nil {
		return err
	}
	err = json.Unmarshal(bs, fc)
	if err != nil {
		return err
	}
	return
}

func NewFeishuClient() *FeishuClient {
	var fc FeishuClient
	err := fc.loadConf()
	if err != nil {
		return nil
	}
	err = fc.GetTenantAccessToken()
	if err != nil {
		service.Log.Sugar().Errorf("feishuUtil未正常获取TenantAccessToken: %s", err.Error())
		return nil
	}
	return &fc
}

func (fc *FeishuClient) SpreadSheets() SpreadSheetsI {
	return fc
}

func (fc *FeishuClient) Message() MessageI {
	return fc
}

func (fc *FeishuClient) loadConf() (err error) {
	// 哈佛企业学习机器人
	fc.appId = "cli_a1addabb4ffa100d"
	fc.appSecret = "RT0g71lbGwQ2ogMHeRiImfmnIg6Z5gzE"
	return
}
